package ccm.itesm.mx.servicios;


import java.util.ArrayList;
import java.util.List;

import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.sqlite.SQLiteStatement;

public class AndroidDAO2 {

   private static final String BASE_DE_DATOS = "donjuan.db";
   private static final int VERSION = 2;
   private static final String UN_TABLA = "empresas";

   private Context context;
   private SQLiteDatabase db;

   private SQLiteStatement insertStmt;
   private static final String INSERT = "insert into "  + UN_TABLA + " (empresa) values (?)";

   public AndroidDAO2(Context context) {
	   OpenHelper open = new OpenHelper(context);
	   db = open.getWritableDatabase();
	   insertStmt = db.compileStatement(INSERT);
   }

   public long insert(String name) {
	   this.insertStmt.bindString(1, name);
	   return this.insertStmt.executeInsert();
   }

   public void deleteAll() {
	   db.delete(UN_TABLA, null, null);
   }

   public List<String> selectAll() {
      List<String> list = new ArrayList<String>();
      Cursor c = this.db.query(UN_TABLA, new String[]{"empresa"}, null, null, null, null, null);
      
      if(c.moveToFirst()){
    	do{
    		list.add(c.getString(0));
    	}
    	while(c.moveToNext());
      }
      return list;
   }

   private static class OpenHelper extends SQLiteOpenHelper {

      OpenHelper(Context context) {
         super(context, BASE_DE_DATOS, null, VERSION);
      }

      @Override
      public void onCreate(SQLiteDatabase db) {
    	  db.execSQL("CREATE TABLE " + UN_TABLA + " (id INTEGER PRIMARY KEY, empresa TEXT)");
      }

      @Override
      public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    	  db.execSQL("DROP TABLE IF EXISTS " + UN_TABLA);
    	  onCreate(db);
      }
   }
}

